import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'

export interface Song {
    id: number
    name: string
    artist: string
    album: string
    duration: number
    cover: string
    url: string
    vip?: boolean
    lyrics?: string
}

export interface LyricLine {
    time: number
    text: string
}

export type PlayMode = 'loop' | 'random' | 'single'

export const useMusicStore = defineStore('music', () => {
    // 音频元素引用
    const audioRef = ref<HTMLAudioElement | null>(null)

    // 播放状态
    const currentSong = ref<Song | null>(null)
    const isPlaying = ref(false)
    const currentTime = ref(0)
    const totalDuration = ref(0)
    const volume = ref(100)
    const playMode = ref<PlayMode>('loop')

    // 歌曲列表
    const songList = ref<Song[]>([])

    // 设置音频元素引用
    const setAudioRef = (audio: HTMLAudioElement) => {
        audioRef.value = audio
        if (audio) {
            audio.volume = volume.value / 100
        }
    }

    // 监听音量变化
    watch(
        volume,
        (newVolume) => {
            if (audioRef.value) {
                audioRef.value.volume = newVolume / 100
            }
        },
        { immediate: true },
    )

    // 监听当前歌曲变化
    watch(currentSong, (newSong) => {
        if (newSong && audioRef.value) {
            audioRef.value.src = newSong.url
            audioRef.value.volume = volume.value / 100
            audioRef.value.load()
            if (isPlaying.value) {
                audioRef.value.play().catch((error) => {
                    console.error('播放失败:', error)
                    message.error('播放失败，请稍后重试')
                    isPlaying.value = false
                })
            }
        }
    })

    // 监听播放状态变化
    watch(isPlaying, (newIsPlaying) => {
        if (audioRef.value) {
            if (newIsPlaying) {
                audioRef.value.play().catch((error) => {
                    console.error('播放失败:', error)
                    message.error('播放失败，请稍后重试')
                    isPlaying.value = false
                })
            } else {
                audioRef.value.pause()
            }
        }
    })

    // 播放歌曲
    const playSong = (song: Song) => {
        currentSong.value = song
        isPlaying.value = true
    }

    // 切换播放/暂停
    const togglePlay = () => {
        if (!currentSong.value) {
            if (songList.value.length > 0) {
                playSong(songList.value[0])
            }
            return
        }
        isPlaying.value = !isPlaying.value
    }

    // 上一首
    const previousSong = () => {
        if (songList.value.length === 0) return

        const currentIndex = currentSong.value ? songList.value.findIndex((s) => s.id === currentSong.value?.id) : -1

        const prevIndex = currentIndex > 0 ? currentIndex - 1 : songList.value.length - 1
        playSong(songList.value[prevIndex])
    }

    // 下一首
    const nextSong = () => {
        if (songList.value.length === 0) return

        if (playMode.value === 'random') {
            // 随机播放
            const randomIndex = Math.floor(Math.random() * songList.value.length)
            playSong(songList.value[randomIndex])
        } else if (playMode.value === 'single') {
            // 单曲循环
            if (currentSong.value) {
                playSong(currentSong.value)
            }
        } else {
            // 列表循环
            const currentIndex = currentSong.value
                ? songList.value.findIndex((s) => s.id === currentSong.value?.id)
                : -1

            const nextIndex = currentIndex < songList.value.length - 1 ? currentIndex + 1 : 0
            playSong(songList.value[nextIndex])
        }
    }

    // 切换播放模式
    const togglePlayMode = () => {
        const modes: PlayMode[] = ['loop', 'random', 'single']
        const modeNames = {
            loop: '列表循环',
            random: '随机播放',
            single: '单曲循环',
        }

        const currentIndex = modes.indexOf(playMode.value)
        playMode.value = modes[(currentIndex + 1) % modes.length]
        message.info(`播放模式: ${modeNames[playMode.value]}`)
    }

    // 进度跳转
    const seek = (time: number) => {
        if (audioRef.value) {
            audioRef.value.currentTime = time
            currentTime.value = time
        }
    }

    // 设置歌曲列表
    const setSongList = (songs: Song[]) => {
        songList.value = songs
    }

    // 音频事件处理
    const onTimeUpdate = () => {
        if (audioRef.value) {
            currentTime.value = Math.floor(audioRef.value.currentTime)
        }
    }

    const onLoadedMetadata = () => {
        if (audioRef.value) {
            totalDuration.value = Math.floor(audioRef.value.duration)
            audioRef.value.volume = volume.value / 100
        }
    }

    const onAudioEnded = () => {
        nextSong()
    }

    const onAudioError = () => {
        console.error('音频加载失败')
        message.error('音频加载失败，自动播放下一首')
        isPlaying.value = false
        setTimeout(() => {
            nextSong()
        }, 1000)
    }

    // 清理
    const cleanup = () => {
        if (audioRef.value) {
            audioRef.value.pause()
            audioRef.value.src = ''
        }
    }

    // 解析 LRC 格式歌词
    const parseLyrics = (lrcString: string): LyricLine[] => {
        if (!lrcString) return []

        const lines = lrcString.split('\n')
        const result: LyricLine[] = []

        const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/g

        for (const line of lines) {
            const matches = [...line.matchAll(timeRegex)]
            if (matches.length === 0) continue

            const text = line.replace(timeRegex, '').trim()
            if (!text) continue

            for (const match of matches) {
                const minutes = parseInt(match[1])
                const seconds = parseInt(match[2])
                const milliseconds = parseInt(match[3])
                const time = minutes * 60 + seconds + milliseconds / (match[3].length === 2 ? 100 : 1000)

                result.push({
                    time,
                    text,
                })
            }
        }

        return result.sort((a, b) => a.time - b.time)
    }

    // 获取当前歌曲的歌词
    const getCurrentLyrics = (): LyricLine[] => {
        if (!currentSong.value || !currentSong.value.lyrics) {
            return []
        }
        return parseLyrics(currentSong.value.lyrics)
    }

    return {
        // 状态
        currentSong,
        isPlaying,
        currentTime,
        totalDuration,
        volume,
        playMode,
        songList,

        // 方法
        setAudioRef,
        playSong,
        togglePlay,
        previousSong,
        nextSong,
        togglePlayMode,
        seek,
        setSongList,
        onTimeUpdate,
        onLoadedMetadata,
        onAudioEnded,
        onAudioError,
        cleanup,
        parseLyrics,
        getCurrentLyrics,
    }
})
